//
//  XDRefreshingView.m
//  TheRicher
//
//  Created by 李晓东 on 2018/1/31.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//

#import "XDRefreshingView.h"

@interface XDRefreshingView ()
@property (nonatomic, strong) CallNetBlock block;
@end
@implementation XDRefreshingView

- (instancetype)initWithFrame:(CGRect)frame andBlock:(CallNetBlock)block{
    if (self = [super initWithFrame:frame]) {
//        [self setBackgroundColor:[UIColor blueColor]];
        [self setAlpha:0.8];
        _block = block;
        CGRect statusFrame = [[UIApplication sharedApplication]statusBarFrame];
        _naviHeight = 64;
        
        CGFloat imgX = (statusFrame.size.width - 55) / 2;
        CGFloat imgY = (_naviHeight - 55) / 5 * 4.5;
        _refreshImgView = [[UIImageView alloc]initWithFrame:CGRectMake(imgX, imgY, 55, 55)];
        [_refreshImgView setImage:[UIImage imageNamed:@"dropdown_anim__0001"]];
        _dragingPicY = _naviHeight + (self.frame.size.height - _refreshImgView.frame.size.height - _refreshImgView.frame.origin.y);
        [self addSubview:_refreshImgView];
        
    }
    return self;
}

- (void)willMoveToSuperview:(UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    
    if (newSuperview && [newSuperview isKindOfClass:[UIScrollView class]]) {
        _tableView = newSuperview;
        [_tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    }
    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentOffset"] && [object isKindOfClass:[UITableView class]]) {
        CGPoint newPoint = [change[NSKeyValueChangeNewKey] CGPointValue];
        CGPoint oldPoint = [change[NSKeyValueChangeOldKey] CGPointValue];
        
        if ([_tableView isDragging]) {
            _isDraged = YES;
            
            if (fabs(newPoint.y) > ((_naviHeight - 55) / 5 * 0.5 + _naviHeight) && fabs(newPoint.y) <= _naviHeight * 2) {
                [self changeLoadingImage:newPoint.y andScrollDirection:(fabs(newPoint.y) - fabs(oldPoint.y)) > 0 ? YES: NO];
            }
        } else if (_isDraged){
            
            if (!_needCall && fabs(newPoint.y) >= (_naviHeight + self.frame.size.height) && newPoint.y < 0) {
                [self resetTablePosition];
            }
            
        }
        
        
    }
}


// 重置 tableView 的 contentInset.top 的位置
- (void)resetTablePosition{
    _needCall = YES;
    CGPoint tableOffset = _tableView.contentOffset;
    UIEdgeInsets tableInsets = _tableView.contentInset;

    #ifdef __IPHONE_11_0
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    #endif
    // 适配 iOS 11,在下拉 tableView 时顶部的空格
//    if (@available(iOS 11.0, *)) {
//        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }
    
    tableInsets.top = _naviHeight + self.frame.size.height;
    _tableView.contentInset = tableInsets;
    _tableView.contentOffset = tableOffset;
    
    
    [_refreshImgView setAnimationImages:@[[UIImage imageNamed:@"eat-1"], [UIImage imageNamed:@"eat-2"], [UIImage imageNamed:@"eat-3"]]];
    [_refreshImgView setAnimationDuration:0.5];
    [_refreshImgView startAnimating];
    
    _block();
    
//    _timer = [NSTimer timerWithTimeInterval:3.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
//        [self recoverTablePosition];
//        if ([_refreshImgView isAnimating]) {
//            [_refreshImgView stopAnimating];
//        }
//    }];
//    [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
}

- (void)stopAnimating{
    
    if ([_refreshImgView isAnimating]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self recoverTablePosition];
            [_refreshImgView stopAnimating];

        });
    }
}

// 恢复 tableView 的 contentInset.top 的位置
- (void)recoverTablePosition {
    UIEdgeInsets tableInsets = _tableView.contentInset;
    tableInsets.top = _naviHeight;
    [UIView animateWithDuration:0.4 animations:^{
        _tableView.contentInset = tableInsets;
        
    } completion:^(BOOL finished) {
        _needCall = NO;
    }];
    
}

- (void)changeLoadingImage:(CGFloat)offsetHeight andScrollDirection:(BOOL)direction{
    
    CGFloat newValue = fabs(offsetHeight) - _dragingPicY <= 60 ? fabs(offsetHeight) - _dragingPicY : 60;
    _refreshImgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%ld", lroundf(newValue)]];
    
}

@end
